<?php

function rpc( $json_request ) {
    global $PARAPARA;

    $req_param = $json_request->param;

    if(!$req_param) {
        return new RPC_Error($json_request->operation, "PARAM", "No params");
    };

    $MAX_SCREENNAME_LEN = 50;
    $MAX_SUBJECT_LEN    = 127;
    $MAX_TEXT_LEN       = 10000;

    $topics  = 'std';
    $subject = $req_param->subject;
    if( !is_string( $subject ) || !strlen( $subject ) || 
        ( strlen( $subject ) > $MAX_SUBJECT_LEN ) )
        return new RPC_Error( $json_request->operation, "PARAM", "subject empty or too long" );

    $text = $req_param->text;
    if( !is_string( $text ) || !strlen( $text ) || 
        ( strlen( $text ) > $MAX_TEXT_LEN ) )
        return new RPC_Error( $json_request->operation, "PARAM", "text empty or too long " );

    $reply_to = $req_param->reply_to;
    if( !is_numeric( $reply_to ) )
        return new RPC_Error( $json_request->operation, "PARAM", "reply_to empty or not numeric " );


    $account = $PARAPARA->fetch_account();

    #### check if anonymous
    if( ( $account == null) && 
        ( $PARAPARA->config_get('FORUM',  'ALLOW_ANONYMOUS') != 'true') ) {
        return new RPC_Error($json_request->operation, "AUTH", "Not authorized to post anonymously");
    }

    if( $ipblock = $PARAPARA->is_ipblocked() ) {
        return new RPC_Error($json_request->operation, "BLOCKED", $ipblock->message );
    }


    $screen_name = '';
    if($PARAPARA->is_logged_in())
        $screen_name = $PARAPARA->get_screen_name();
    else {
        $screen_name = $req_param->screen_name;
        if( !is_string( $screen_name ) || !strlen( $screen_name ) || 
            ( strlen( $screen_name ) > $MAX_SCREENNAME_LEN ) )
            return new RPC_Error( $json_request->operation, "PARAM", "screen_name empty or too long" );
    }

    // Fetch message from the database to find out the thread_id and check whether it's still there:
    $dbl     = $PARAPARA->dblayer;
    $message = $dbl->get_forum_message( $reply_to );
    if(!$message )    {
            return new RPC_Error( $json_request->operation, "NOTFOUND", "Message not found" );        
    }

    $thread_id   = $message->thread_id;
    $user_id     = $PARAPARA->get_uid();
    $ip          = $PARAPARA->remote_addr;


    $status = $dbl->create_forum_message( $thread_id, $reply_to, $screen_name,
                                          $user_id,   $subject,  $text,        $ip
        );


    if( !$status ) {
        return new RPC_Error($json_request->operation, "INTERNAL", "Internal error");
    }


    $rpc_retval = array( 'status'      => 'ok', 
                         'message_id'  => $status,
                         'thread_id'   => $thread_id
      );

    return new RPC_Response( $json_request->operation, $rpc_retval );

}

return rpc( $json_request );

?>